package com.yz.util;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Request.Builder;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OkHttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);

    private static OkHttpClient okHttpClient;


    public static StringBuffer getQueryString(String url, Map<String, String> queries) {
        StringBuffer sb = new StringBuffer(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries.entrySet().iterator();

            while(iterator.hasNext()) {
                Entry entry = (Entry)iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }

        return sb;
    }

    private static String execNewCall(Request request) {
        Response response = null;

        String var3;
        try {
            response = getOkHttpClient().newCall(request).execute();
            int status = response.code();
            if (!response.isSuccessful()) {
                return "";
            }

            var3 = response.body().string();
        } catch (Exception e) {
            logger.error("okhttp3 put error >> ex = {}", ExceptionUtils.getStackTrace(e));
            return "";
        } finally {
            if (response != null) {
                response.close();
            }

        }

        return var3;
    }

    public static String get(String url, Map<String, String> queries) {
        StringBuffer sb = getQueryString(url, queries);
        Request request = (new Builder()).url(sb.toString()).build();
        return execNewCall(request);
    }

    public static String postFormParams(String url, Map<String, String> params) {
        okhttp3.FormBody.Builder builder = new okhttp3.FormBody.Builder();
        if (params != null && params.keySet().size() > 0) {
            Iterator var3 = params.keySet().iterator();
            while(var3.hasNext()) {
                String key = (String)var3.next();
                builder.add(key, (String)params.get(key));
            }
        }

        Request request = (new Builder()).url(url).post(builder.build()).build();
        return execNewCall(request);
    }

    public static String postJsonParams(String url, String jsonParams) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = (new Builder()).url(url).post(requestBody).build();
        return execNewCall(request);
    }

    public static String postXmlParams(String url, String xml) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
        Request request = (new Builder()).url(url).post(requestBody).build();
        return execNewCall(request);
    }

    public static OkHttpClient getOkHttpClient() {
        //是否开启缓存、连接池
        return okHttpClient == null ?new OkHttpClient.Builder()
                .sslSocketFactory(OkHttpUtil.sslSocketFactory(), OkHttpUtil.x509TrustManager())
                .retryOnConnectionFailure(false)
                .connectionPool(OkHttpUtil.pool())
                .connectTimeout(10L, TimeUnit.SECONDS)
                .readTimeout(10L, TimeUnit.SECONDS)
                .build()
        : okHttpClient;
    }

    public static X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }

    public static SSLSocketFactory sslSocketFactory() {
        try {
            //信任任何链接
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static ConnectionPool pool() {
        return new ConnectionPool(200, 5, TimeUnit.MINUTES);
    }

    public static void setOkHttpClient(OkHttpClient okHttpClient) {
        OkHttpUtil.okHttpClient = okHttpClient;
    }
}
